#pragma once

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <queue>
#include "Cond.hpp"
#include "Mutex.hpp"

const static int gcap = 5;

template <typename T>
class BlockQueue
{
public:
    BlockQueue(const int cap = gcap) : _cap(cap), _consumer_wait_num(0), _productor_wait_num(0)
    {
    }
    ~BlockQueue()
    {
    }
    bool IsFull()
    {
        return _bq.size() >= _cap;
    }
    bool IsEmpty()
    {
        return !_bq.size();
    }
    void Pop(T *out)
    {
        {
            LockGuard lockguard(&_lock);
            while (IsEmpty()) // while循环 防止1. pthread_cond_wait调用失败 2.伪唤醒问题
            {
                _consumer_wait_num++;
                _c_cond.Wait(_lock);
                _consumer_wait_num--;
            }
            *out = _bq.front();
            _bq.pop();

            if (_productor_wait_num > 0)
                _p_cond.NotifyOne();
        }
    }

    void Enqueue(const T &in)
    {
        {
            LockGuard lockguard(&_lock);
            while (IsFull())
            {
                _productor_wait_num++;
                _p_cond.Wait(_lock);
                _productor_wait_num--;
            }
            _bq.push(in);

            if (_consumer_wait_num > 0)
                _c_cond.NotifyOne();
        }
    }

private:
    // 临界资源
    std::queue<T> _bq;
    int _cap;
    Mutex _lock;

    Cond _p_cond;
    Cond _c_cond;

    int _productor_wait_num;
    int _consumer_wait_num;
};